import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';

export class AddWechatFieldsToUsers1730626000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // 修改现有字段为可空
    await queryRunner.changeColumn(
      'users',
      'username',
      new TableColumn({
        name: 'username',
        type: 'varchar',
        length: '50',
        isNullable: true,
        isUnique: true,
        comment: '用户名',
      }),
    );

    await queryRunner.changeColumn(
      'users',
      'email',
      new TableColumn({
        name: 'email',
        type: 'varchar',
        length: '100',
        isNullable: true,
        isUnique: true,
        comment: '邮箱',
      }),
    );

    await queryRunner.changeColumn(
      'users',
      'md5password',
      new TableColumn({
        name: 'md5password',
        type: 'varchar',
        length: '255',
        isNullable: true,
        comment: '密码',
      }),
    );

    // 添加微信相关字段
    await queryRunner.addColumn(
      'users',
      new TableColumn({
        name: 'openid',
        type: 'varchar',
        length: '100',
        isNullable: true,
        isUnique: true,
        comment: '微信 openid',
      }),
    );

    await queryRunner.addColumn(
      'users',
      new TableColumn({
        name: 'unionid',
        type: 'varchar',
        length: '100',
        isNullable: true,
        isUnique: true,
        comment: '微信 unionid',
      }),
    );

    await queryRunner.addColumn(
      'users',
      new TableColumn({
        name: 'nickname',
        type: 'varchar',
        length: '100',
        isNullable: true,
        comment: '微信昵称',
      }),
    );

    // 创建索引
    await queryRunner.query(
      'CREATE INDEX `IDX_users_openid` ON `users` (`openid`)',
    );
    await queryRunner.query(
      'CREATE INDEX `IDX_users_unionid` ON `users` (`unionid`)',
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 删除索引
    await queryRunner.query('DROP INDEX `IDX_users_unionid` ON `users`');
    await queryRunner.query('DROP INDEX `IDX_users_openid` ON `users`');

    // 删除微信相关字段
    await queryRunner.dropColumn('users', 'nickname');
    await queryRunner.dropColumn('users', 'unionid');
    await queryRunner.dropColumn('users', 'openid');

    // 恢复字段为非空（如果需要的话，这里保持可空状态更安全）
    // 注意：恢复为非空可能会失败，如果表中已有微信登录用户
  }
}
